from sqlalchemy import Column, Integer, DateTime, ForeignKey, UniqueConstraint
from sqlalchemy.sql import func
from sqlalchemy.orm import relationship

from app.core.database import Base


class UserWatchlist(Base):
    """用户自选股模型"""
    __tablename__ = "user_watchlist"
    
    id = Column(Integer, primary_key=True, index=True)
    user_id = Column(Integer, ForeignKey("users.id"), nullable=False)
    stock_id = Column(Integer, ForeignKey("stocks.id"), nullable=False)
    added_at = Column(DateTime(timezone=True), server_default=func.now())
    
    # 关系
    user = relationship("User", back_populates="watchlists")
    stock = relationship("Stock", back_populates="watchlists")
    
    # 确保用户不能重复添加同一只股票
    __table_args__ = (
        UniqueConstraint('user_id', 'stock_id', name='unique_user_stock'),
    )
    
    def __repr__(self):
        return f"<UserWatchlist(id={self.id}, user_id={self.user_id}, stock_id={self.stock_id})>"